<template>
  <div>
    <el-row>
      <el-col :span="8">
        <el-form-item label="sku">
          <el-input maxlength="20" show-word-limit v-model.trim="formInline.productspeccode" placeholder=""  @blur="validateSKU"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item :label="$t('m.page.location')">
          <el-input maxlength="20" show-word-limit v-model.trim="formInline.locationcode" placeholder="" @blur="validateLocation" :disabled="!hasSKU"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item :label="$t('m.inventory.checkqty')">
          <el-input v-input-valid maxlength="20" show-word-limit v-model.number="formInline.checkqty" :disabled="!formInline.locationcode"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24" align="right">
        <el-button type="primary" @click="saveCheckqty">{{$t('m.inventory.saveCheckqty')}}</el-button>
      </el-col>
    </el-row>
    <!-- table数据展示 start -->
    <el-row>
      <el-col :span="24">
        <el-table
          empty-text
          fit
          class="table-wrap"
          size="mini"
          :span-method="objectSpanMethod"
          :data="tableData">
          <el-table-column align="center" type="index" :label="$t('m.index')" width="50"></el-table-column>
          <el-table-column align="center" prop="productspeccode" label="SKU" width="150"></el-table-column>
          <el-table-column align="center" prop="locationcode" :label="$t('m.location.locationcode')" width="150"></el-table-column>
          <!-- 暂时封存实际数量，明盘功能才会用到 -->
          <!-- <el-table-column align="center" prop="" label="实际数量"></el-table-column> -->
          <el-table-column align="center" :label="$t('m.state')" width="100">
            <template slot-scope="scope">{{!scope.row.state?$t('m.inventory.state2'):$t('m.inventory.state1')}}</template>
          </el-table-column>
          <el-table-column align="center" prop="checkqty" :label="$t('m.inventory.checkqty')" width="100"></el-table-column>
          <el-table-column align="center" prop="productname" :label="$t('m.in.productname')"></el-table-column>
          <el-table-column align="center" prop="productspec" :label="$t('m.in.productspec')" width="200"></el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <!-- table数据展示 end -->
    <!-- 盘点结果原因选择 dialog 开始 -->
    <el-dialog width="30%" :title="$t('m.inventory.result')" :visible.sync="reasonPopupVisible" :before-close="close" append-to-body center>
    <el-form ref="formInline" size="medium" :model="formInline" label-width="120px">
      <el-row>
        <el-col :span="20">
          <el-form-item :label="$t('m.inventory.result')">
            <el-input v-model="checkresultFilters" disabled></el-input>
          </el-form-item>
          <el-form-item v-if="checkresult === 2" :label="$t('m.inventory.lossreason')" required>
            <el-select v-model="reasonid" :placeholder="$t('m.choose')" filterable>
              <el-option
                v-for="(item,index) in lossOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="checkresult ===1" :label="$t('m.inventory.surplusreason')" required>
            <el-select v-model="reasonid" :placeholder="$t('m.choose')" filterable>
              <el-option
                v-for="(item,index) in surplusOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="close">{{$t('m.cancel')}}</el-button>
      <el-button @click="confirmCheckqty" type="primary">{{$t('m.confirm')}}</el-button>
    </span>
  </el-dialog>
  <!-- 盘点结果原因选择 dialog 结束 -->

  </div>
</template>
<script>
export default {
  name:'inventory-sku-detail',
  data(){
    return {
      formInline:{
        locationcode:'', // 库位
        productspeccode:'', // sku
        checkqty:0 // 盘点数量
      },
      checkresult:'', // 盘点结果(1、盘盈 2、盘亏)
      reasonid:'', // 盘盈盘亏原因id
      reason:'', // 盘盈盘亏原因
      tableData:[],
      reasonDetail:[],
      getMergeRows:[], // 获取table的合并行信息

      hasSKU:false, // tableData中是否存在输入的sku
      reasonPopupVisible:false //盘盈盘亏原因 dialog 显示隐藏
    }
  },
  inject:{
    getInventoryDetail:{
      default:()=>{}
    }
  },
  mounted(){
    this.tableData = this.cloneObject(this.getInventoryDetail().stockTakeDetailOutputList)
    // 表格数据排序
    this.tableData.sort((prev,cur)=>{
      if(prev.productid < cur.productid) return 1
      else if(prev.productid > cur.productid) return -1
      else return 0
    })
    this.ruleSpanMethod() // 表格缩进规则
  },
  computed:{
    checkresultOptions(){
      return [
        // 盘点结果
        { label:this.$t('m.inventory.surplus'), value:1 },
        { label:this.$t('m.inventory.loss'), value:2 }
      ]
    },
    lossOptions(){
      return [
        // 盘亏原因
        { label:this.$t('m.inventory.reason1'), value:1 },
        { label:this.$t('m.inventory.reason2'), value:2 },
        { label:this.$t('m.inventory.reason3'), value:3 },
        { label:this.$t('m.inventory.reason4'), value:4 },
        { label:this.$t('m.inventory.reason5'), value:5 },
        { label:this.$t('m.inventory.reason6'), value:6 }
      ]
    },
    surplusOptions(){
      return [
        // 盘盈原因
        { label:this.$t('m.inventory.reason1'), value:1 },
        { label:this.$t('m.inventory.reason6'), value:6 }
      ]
    },
    checkresultFilters(){
      return this.checkresult === 1 ? this.$t('m.inventory.surplus'):this.$t('m.inventory.loss')
    }
  },
  methods:{
    close(){
      this.reasonid = ''
      this.reason = ''
      this.reasonPopupVisible = false
    },
    completeCallback(){
      this.$emit('callback')
    },
    // 表格缩进规则
    ruleSpanMethod(){
      let __index = 0
      let code = ''
      this.getMergeRows = []
      this.tableData.forEach((item,index)=>{
        if(!item.productspeccode){
          this.getMergeRows.push(1)
        } else if(item.productspeccode !== code){
          this.getMergeRows.push(1)
          code = item.productspeccode
          __index = index
        } else {
          if(code){
            ++this.getMergeRows[__index]
            this.getMergeRows.push(0)
          }
        }
      })
    },
    // 表格缩进
    objectSpanMethod({ rowIndex, columnIndex }){
      let MergeArr = [1,5,6]
      if (MergeArr.includes(columnIndex)){
        if(!this.getMergeRows.length){
          return {
            rowspan:1,
            colspan:1
          }
        } else {
          return {
            rowspan:this.getMergeRows[rowIndex],
            colspan:this.getMergeRows[rowIndex] ? 1 : 0
          }
        }
      }
    },
    // tableData中是否存在传入的信息（sku or locationcode）
    getValidateResult(key){
      return this.tableData.some((item)=>{
        return item[key] === this.formInline[key]
      })
    },
    // 验证sku是否存在于当前表格中
    validateSKU(){
      if(!this.formInline.productspeccode) return this.callbackMessage(this.$t('m.enter')+'SKU')
      // 这块纯粹是优化用户体验
      if(this.getValidateResult('productspeccode')){
        this.hasSKU=true
      } else {
        this.hasSKU=false
        this.callbackMessage(this.$t('m.inventory.noSKU'))
      }
    },
    // 验证库位编码是否存在于当前表格中
    validateLocation(){
      if(!this.formInline.locationcode) return this.callbackMessage(this.$t('m.enter')+this.$t('m.location.locationcode'))
    },
    // 保存单项盘点数据
    saveCheckqty(){

      if(!this.formInline.productspeccode) return this.callbackMessage(this.$t('m.enter')+'SKU')
      if(!this.formInline.locationcode) return this.callbackMessage(this.$t('m.enter')+this.$t('m.location.locationcode'))
      if(!this.hasSKU) return this.callbackMessage(this.$t('m.inventory.noSKU'))
      if(this.formInline.checkqty==='') return this.callbackMessage(this.$t('m.enter')+this.$t('m.inventory.checkqty'))
      if(isNaN(this.formInline.checkqty)) return this.callbackMessage(this.$t('m.inventory.number'))
      if(this.formInline.checkqty<0) return this.callbackMessage(this.$t('m.inventory.number'))
      // 过滤出当前需要操作的sku list
      let targetSkuList = this.tableData.filter((item)=>{
        return item.productspeccode === this.formInline.productspeccode
      })
      let hasLocationCode = targetSkuList.some((item)=>{
        return item.locationcode === this.formInline.locationcode
      })
      // 如果该库位不存在于当前盘点单中，新增一条记录
      if(!hasLocationCode){
        this.$confirm(this.$t('m.inventory.addInventory'), this.$t('m.noticemessage'), {
          confirmButtonText:this.$t('m.confirm'),
          cancelButtonText:this.$t('m.cancel'),
          type:'warning'
        }).then(() => {
          new Promise((resolve,reject)=>{
            this.validateMaxInventory(resolve,reject) // 验证：是否存在库位 && 是否超出该库位最大物理容纳量
          }).then(()=>{
            let {productid,productname,productspec,suppliercode} = this.tableData.find((item)=>{ // 新插入一条记录，sku的明细数据也要提交
              return item.productspeccode === this.formInline.productspeccode
            })
            if(this.formInline.checkqty<=0) return this.callbackMessage(this.$t('m.inventory.number'))
            let options = {
              method:'post',
              url:`/stocktake/makestocktakingforone`,
              data:{
                checkqty:this.formInline.checkqty,
                locationcode:this.formInline.locationcode,
                productspeccode:this.formInline.productspeccode,
                stocktakeid:this.getInventoryDetail().stocktakeid,
                storage:0,
                state:0,
                productid,
                productname,
                productspec,
                suppliercode
              }
            }
            let tempTableData = this.cloneObject(this.tableData)
            let length = tempTableData.length
            let index = tempTableData.reverse().findIndex((item)=>{
              return item.productspeccode === this.formInline.productspeccode
            })
            this.$axios(options).then(({ data,message }) => {
              this.tableData.splice(length - index,0,data)
              this.ruleSpanMethod() // 表格缩进规则
              this.saveCheckqtyCallback(message)
            })
          }).catch(()=>{

          })
        }).catch(() => {
          this.callbackMessage(this.$t('m.inventory.state4'),'info')
        })
      } else {

        let options = {
          method:'get',
          url:`/stocktake/ifsurplus`,
          params:this.formInline
        }
        this.tableLoading = true
        this.$axios(options).then(({ data }) => {
          this.checkresult = data
          if(this.checkresult===0){
            this.reasonPopupVisible = false
            this.confirmCheckqty()
          }else{
            this.reasonPopupVisible = true
          }
          setTimeout(()=>this.tableLoading=false,500)
        })

      }
    },

    confirmCheckqty(){
      new Promise((resolve,reject)=>{
        this.validateMaxInventory(resolve,reject)
      }).then(()=>{
        let __index = 0
        let {stocktakedetailid} = this.tableData.find((item,index)=>{
          if(item.locationcode === this.formInline.locationcode && item.productspeccode === this.formInline.productspeccode) __index = index
          return item.locationcode === this.formInline.locationcode && item.productspeccode === this.formInline.productspeccode
        })
        let reason = this.checkresult===0? '' : this.lossOptions.find((item) => item.value === this.reasonid).label
        let options = {
          method:'post',
          url:`/stocktake/makestocktakingforone`,
          data:{
            stocktakedetailid,
            checkqty:this.formInline.checkqty,
            checkresult:this.checkresult,
            reasonid:this.reasonid,
            reason
          }
        }
        this.$axios(options).then(({ data,message }) => {
          let {checkqty} = data || this.formInline
          this.$set(this.tableData[__index],'checkqty',checkqty)
          this.$set(this.tableData[__index],'state',1)

          this.saveCheckqtyCallback(message)
        })
      })
    },
    // 保存后回调（通用方法）
    saveCheckqtyCallback(message){
      // 重置输入环境
      this.hasSKU = false
      this.formInline.locationcode = this.formInline.productspeccode = ''
      this.formInline.checkqty = 0
      this.reasonid = ''
      this.reason = ''
      this.reasonPopupVisible = false
      // 判断是否已经全部录入
      let isCompleted = this.tableData.every((item)=>{
        return item.state === 1
      })
      // 如果所有盘点单都完成，该单自动进入盘点历史
      isCompleted?this.callbackMessage(this.$t('m.inventory.complete'),'success',2000,this.completeCallback):this.callbackMessage(message,'success')
    },
    validateMaxInventory(resolve,reject){
      // 验证是否超出该库位最大物理容纳量
      let options = {
        method:'get',
        url:`/stocktake/checklocvalidity`,
        params:{
          checkqty:this.formInline.checkqty,
          locationcode:this.formInline.locationcode,
          productspeccode:this.formInline.productspeccode
        }
      }
      this.$axios(options).then(({ code }) => {
        if (code === 0){
          resolve()
        } else {
          reject()
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>

</style>